package com.imtimmy.android.whichone;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class Whichone extends Activity implements LocationListener {

	private static final int SHAKE_THRESHOLD = 5000;
	private ArrayList<String> list;
	private ArrayAdapter<String> adapter;
	private SensorManager sManager;

	private ListView listView;
	private long lastResultTime;

	// 检测摇动相关变量
	private long lastTime = 0;
	private long curTime = 0;
	private long duration = 0;
	private float last_x = 0.0f;
	private float last_y = 0.0f;
	private float last_z = 0.0f;
	private float shake = 0.0f;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		list = new ArrayList<String>();
		loadData();

		// String query = "餐厅";
		// try {
		// getMapData(query);
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (JSONException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		setContentView(R.layout.main);
		listView = (ListView) findViewById(R.id.lv_items);
		listView.setOnItemClickListener(listItemClickListener);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, list);
		listView.setAdapter(adapter);

		sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		Sensor accelerometerSensor = sManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		sManager.registerListener(accelerometerSensorEventListener,
				accelerometerSensor, SensorManager.SENSOR_DELAY_UI);

		Log.e("create", "create");

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		sManager.unregisterListener(accelerometerSensorEventListener);
		super.onDestroy();
	}

	private OnItemClickListener listItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub

			String item = list.get(position);
			Bundle bundle = new Bundle();
			bundle.putInt("position", position);
			bundle.putString("name", item);
			showDialog(0, bundle);

		}
	};

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final Bundle bundle = args;
		builder.setMessage("Are you sure to delete this item?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								int position = bundle.getInt("position");
								String name = bundle.getString("name");
								list.remove(position);
								adapter.notifyDataSetChanged();
								deleteData(name);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		return alert;

		// return super.onCreateDialog(id, args);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "Add");

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			Intent intent = new Intent(this, AddData.class);
			startActivityForResult(intent, 10);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void loadData() {
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		Cursor cs = db.query(DatabaseHelper.TABLE_NAME,
				new String[] { "name" }, null, null, null, null, null);
		if (cs.moveToFirst()) {
			int nIndex = cs.getColumnIndex("name");
			do {
				String item = cs.getString(nIndex);
				list.add(item);
			} while (cs.moveToNext());
		}
		cs.close();
		db.close();
		dbHelper.close();
	}

	private void insertData(String data) {
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("name", data);
		db.insert(DatabaseHelper.TABLE_NAME, null, cv);
		db.close();
		dbHelper.close();
	}

	private void deleteData(String data) {
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String where = "name='" + data + "'";
		db.delete(DatabaseHelper.TABLE_NAME, where, null);
		db.close();
		dbHelper.close();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Log.e("GOT RESULT", "GOT");

		switch (resultCode) {
		case 10:
			Bundle bundle = data.getExtras();
			String name = bundle.getString("name");
			insertData(name);
			list.add(name);
			adapter.notifyDataSetChanged();
			break;

		default:
			break;
		}

	}

	private SensorEventListener accelerometerSensorEventListener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			// TODO Auto-generated method stub
			synchronized (this) {

				// 获取当前时刻的毫秒数
				curTime = System.currentTimeMillis();
				if (curTime - lastResultTime < 2000) {
					return;
				}
				// 100毫秒检测一次
				if ((curTime - lastTime) > 100) {
					duration = (curTime - lastTime);
					// 获取加速度传感器的三个参数
					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];

					shake = (Math.abs(x - last_x) + Math.abs(y - last_y) + Math
							.abs(z - last_z)) / duration * 10000;
					Log.d("sensor", "shake detected w/ speed: " + shake);
					if (shake > SHAKE_THRESHOLD) {
						lastResultTime = curTime;
						ShowResult();
						initShake();
						// gotOne = true;
						// initShake();
					}

					//
					// // 把每次的晃动幅度相加，得到总体晃动幅度
					// totalShake += shake;
					//
					// // 判断是否为摇动，这是我自己写的标准，不准确，只是用来做教学示例，别误会了^_^
					// if (totalShake > 10
					// && totalShake / (curTime - initTime) * 1000 > 10) {
					// ShowResult();
					// initShake();
					// }
					//
					// Log.i("ShakeInfo", "总体晃动幅度=" + totalShake + "\n平均晃动幅度="
					// + totalShake / (curTime - initTime) * 1000);
					last_x = x;
					last_y = y;
					last_z = z;
					lastTime = curTime;
				}
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}
	};

	private void ShowResult() {
		Random random = new Random();
		int itemIndex = Math.abs(random.nextInt() % (list.size() - 1));
		// Log.i("position", String.valueOf(itemIndex));
		String name = list.get(itemIndex);

		Intent intent = new Intent(this, Result.class);
		intent.putExtra("name", name);
		startActivity(intent);
		// overridePendingTransition(android.R.anim., exitAnim)
	}

	// 摇动初始化
	private void initShake() {
		lastTime = 0;
		duration = 0;
		last_x = 0.0f;
		last_y = 0.0f;
		last_z = 0.0f;
		shake = 0.0f;
	}

	private void getMapData(String query) throws IOException, JSONException {
		String sll = "sll=" + getLocation();

		String encodeQuery = URLEncoder.encode(query, "utf-8");
		URL url = new URL(
				"http://ajax.googleapis.com/ajax/services/search/local?"
						+ "v=1.0&rsz=8&" + sll + "&q=" + encodeQuery);
		URLConnection connection = url.openConnection();
		// connection.addRequestProperty("Referer", /* Enter the URL of your
		// site here */);

		String line;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		while ((line = reader.readLine()) != null) {
			builder.append(line);
		}

		Log.i("JSON", url.toString());
		JSONObject json = (JSONObject) new JSONTokener(builder.toString())
				.nextValue();
		JSONObject json2 = json.getJSONObject("responseData");
		JSONArray jArray = json2.getJSONArray("results");
		ArrayList<String> titleArray = new ArrayList<String>();
		for (int i = 0; i < jArray.length(); i++) {
			JSONObject object = jArray.getJSONObject(i);
			String titleObj = object.getString("title");
			Log.i("JSON", titleObj);
			list.add(titleObj);
		}

	}

	private String getLocation() {
		LocationManager lManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String provider = lManager.getBestProvider(criteria, true);
		// In order to make sure the device is getting the location, request
		// updates.
		lManager.requestLocationUpdates(provider, 1, 0, this);
		Location location = lManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		lManager.removeUpdates(this);
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		String sll = lat + "," + lng;

		return sll;

	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

}